﻿using System;
using System.Text;
using RAP.Framework.Libary.ServerCacheManager;
using RAP.Framework.Libary.Utils;
using RAP.Framework.Libary.DomTemplateBuilder.Element.Cache;
using RAP.Framework.Libary.DomTemplateBuilder.Interface;

namespace RAP.Framework.Libary.DomTemplateBuilder.Handler.Cache
{
	/// <summary>
	/// 获取指定键的缓存保存到指定属性中
	/// </summary>
	public class GetCacheHandler : CacheHandlerBase
	{
        

		public override void DoRender ( StringBuilder writer, object rootParamObject, object parentParamObject, ITemplateRenderContext context )
		{
			var ele = this.Element as GetCache;
			var cacheKey = this.GetFieldName ( rootParamObject, parentParamObject, context );
			if ( cacheKey.IsNullOrEmpty ( ) )
			{
				throw new NullReferenceException ( "CacheKey不能为空！" );
			}
			var cacheValue = CacheManager.Instance.Get ( cacheKey );
			if ( cacheValue.IsNullOrEmpty ( ) && ele.DefaultValue != null )
			{
				var defaultValue = new StringBuilder ( );
				ele.DefaultValue.Handler.DoRender ( defaultValue, rootParamObject, parentParamObject, context );
				cacheValue = this.GetConvertedValue ( defaultValue.ToString ( ) );
			}
			else
			{
				cacheValue = this.GetConvertedValue ( cacheValue );
			}
			var propertyName = this.GetPropertyName ( rootParamObject, parentParamObject, context );
			if ( propertyName.IsNotNullOrEmpty ( ) )
			{
				var paramObj = this.GetParamObject ( rootParamObject, parentParamObject, context );
				if ( paramObj.IsNullOrEmpty ( ) )
				{
					throw new NullReferenceException ( "Property：{0} 指定的对象不存在！".format ( this.Property ) );
				}
				paramObj.SetValue ( propertyName, cacheValue );
			}
			else
			{
				writer.Append ( cacheValue.ToJSON ( ) );
			}
		}

        public override string GetPropertyName( object rootParamObject, object parentParamObject, ITemplateRenderContext context )
        {
            return ExpressionUtils.GetFieldName( this.FieldName, rootParamObject, parentParamObject, context );
        }
    }
}
